package com.luke.xiaotiaowa.modules.oss;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * oss 业务实现类
 *
 * @author xiaotiaowa
 * @create 2023/4/4
 */
@Service
public class OssServiceImpl implements OssService {

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.file.keyid}")
    private String keyId;
    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;
    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Override
    public String upload(MultipartFile file) {
        OSS ossClient = null;
        try {
            var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            var is = file.getInputStream();
            var filename = file.getOriginalFilename();
            filename = UUID.randomUUID().toString().replaceAll("-", "") + filename;
            var uploadFilename = LocalDate.now().format(formatter) + "/" + filename;
            ossClient.putObject(bucketName, uploadFilename, is);
            return "https://" + bucketName + "." + endpoint + "/" + uploadFilename;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }
    }
}
